import random
import string

from django.shortcuts import render
from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from django.http import HttpResponse, JsonResponse  # 返回状态
# 分页所需的包
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.core.signing import Signer  # 签名
from django.core.cache import cache  # 缓存
from datetime import timedelta  # 超时
from .models import customers, orders


# Create your views here.
def creat_token(name):
    randomstr = ''.join(random.choices(string.ascii_letters, k=8))
    token = Signer().sign(randomstr + name)
    cache.set(f'test_{name}', token, timeout=timedelta(minutes=100).total_seconds())
    return token


def check_token(request):
    reqtoken = request.META.get('HTTP_TOKEN')
    if reqtoken is None:
        return False, 'xxxx'
    untoken = Signer().unsign(reqtoken)
    name = untoken[8:]
    cachetoken = cache.get(f'test_{name}')
    if cachetoken is None:
        return False, 'xxxx'
    return True, name


@api_view(['post'])
def login(request):
    data = JSONParser().parse(request)
    email = data.get('email')
    password = data.get('password')
    if customers.objects.filter(email=email).exists() is False:
        return JsonResponse({
            'code': 404,
            'msg': "用户不存在"
        })
    obj = customers.objects.get(email=email)
    if obj.password != password:
        return JsonResponse({
            'code': 400,
            'msg': "密码错误"
        })
    token = creat_token(email)
    return JsonResponse({
        'code': 200,
        'msg': "登录成功",
        'token': token
    })

def is_empty(n):
    return n is None or str(n).strip() == ''
@api_view(['post'])
def add_order(request):
    flag, name = check_token(request)
    if flag is False:
        return JsonResponse({'code': 401, 'msg': "未登录，请先登录"})
    data = JSONParser().parse(request)
    product_name = data.get('name')
    quantity = data.get('num')
    price = data.get('price')
    customer_id = data.get('user_id')
    status = data.get('status')
    if is_empty(product_name) or is_empty(quantity) or is_empty(price) or is_empty(customer_id):
        return JsonResponse({
            'code': 403,
            'msg': "参数项必填"
        })
    if customers.objects.filter(id=customer_id).exists() is False:
        return JsonResponse({
            'code': 404,
            'msg': "用户不存在"
        })
    orders(product_name=product_name,quantity=quantity,price=price,customer_id_id=customer_id,status=status).save()
    return JsonResponse({
        'code': 200,
        'msg': "订单添加成功"
    })

# daimact















